package simpledb;


/**
 * The delete operator.  Delete reads tuples from its child operator and
 * removes them from the table they belong to.
 */
public class Delete extends AbstractDbIterator {

    TransactionId  transactionId  ;
    DbIterator dbIterator  ;

    Tuple resultTuple ;
    boolean isFirst = false  ;

    /**
     * Constructor specifying the transaction that this delete belongs to as
     * well as the child to read from.
     * @param t The transaction this delete runs in
     * @param child The child operator from which to read tuples for deletion
     */
    public Delete(TransactionId t, DbIterator child) {
        // some code goes here

        this.transactionId = t ;
        this.dbIterator = child ;

        Type types[] = new Type[]{ Type.INT_TYPE };
        TupleDesc tupleDesc  = new TupleDesc( types );
        resultTuple = new Tuple( tupleDesc ) ;

        isFirst = true;
    }

    public TupleDesc getTupleDesc() {
        // some code goes here
        return resultTuple.getTupleDesc() ;
    }

    public void open() throws DbException, TransactionAbortedException {
        // some code goes here
        this.dbIterator.open();
    }

    public void close() {
        // some code goes here
        this.dbIterator.close();
    }

    public void rewind() throws DbException, TransactionAbortedException {
        // some code goes here
        this.dbIterator.rewind();
    }

    /**
     * Deletes tuples as they are read from the child operator. Deletes are
     * processed via the buffer pool (which can be accessed via the
     * Database.getBufferPool() method.
     * @return A 1-field tuple containing the number of deleted records.
     * @see Database#getBufferPool
     * @see BufferPool#deleteTuple
     */
    protected Tuple readNext() throws TransactionAbortedException, DbException {
        // some code goes here

        if( !this.dbIterator.hasNext() ) {
            if (isFirst) {
                isFirst = false;
                resultTuple.setField(0, new IntField(0));
                return resultTuple ;
            }else{
                return null ;
            }
        }

        int countResult = 0;
        while( this.dbIterator.hasNext() ) {
            try {
                Database.getBufferPool().deleteTuple( this.transactionId , this.dbIterator.next() );
                countResult++ ;
            } catch (TransactionAbortedException e) {
                e.printStackTrace();
            }
        }
        isFirst = false;
        resultTuple.setField(0 , new IntField(countResult) );

        return resultTuple ;
    }


}
